package com.fzx.fzwsupplysystem.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.fzx.fzwsupplysystem.MyApplication;
import com.fzx.fzwsupplysystem.R;
import com.fzx.fzwsupplysystem.bean.PersonBean;
import com.fzx.fzwsupplysystem.util.AppConstant;
import com.fzx.fzwsupplysystem.util.CountTimes;
import com.fzx.fzwsupplysystem.util.LogUtil;
import com.fzx.fzwsupplysystem.util.ToastUtil;
import com.fzx.fzwsupplysystem.view.CountTimeTextView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import net.posprinter.posprinterface.IMyBinder;
import net.posprinter.posprinterface.ProcessData;
import net.posprinter.posprinterface.TaskCallback;
import net.posprinter.service.PosprinterService;
import net.posprinter.utils.BitmapProcess;
import net.posprinter.utils.BitmapToByteData;
import net.posprinter.utils.DataForSendToPrinterPos80;
import net.posprinter.utils.PosPrinterDev;
import net.posprinter.utils.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class PersonalInfoActivity extends BaseActivity {

    private static final String TAG = "PersonalInfoActivity";
    private LinearLayout ll_value;
    private List<String> valueList;

    private CountTimeTextView tv_count;
    private Button btn_print;
    private PersonBean personBean;

    public IMyBinder myBinder;
    private boolean isConnect = false;

    private boolean isBindService = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_info);
        initView();
        bindService();
        Intent intent = getIntent();
        personBean = (PersonBean) intent.getSerializableExtra("PersonBean");

        valueList = new ArrayList<>();

        testData();

    }

    private void initView() {
        ll_value = findViewById(R.id.ll_value);
        tv_count = findViewById(R.id.tv_count);
        btn_print = findViewById(R.id.btn_print);
        btn_print.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isBindService || !isConnect) {
                    ToastUtil.showToast(getApplicationContext(), "正在连接打印机。。。");
                    return;
                }
                // TODO: 2019/11/14 点击打印，弹框提示“是否确认信息准确” ，点击是进行打印，否留在当前页，信息有误的，点击对应的信息，弹框提示“请咨询现场工作人员进行修改！”
                showYNDialog("是否确认信息准确", "是", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //print
                        hideMessageDialog();
                        print();
                    }
                }, "否 ", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        hideMessageDialog();
                    }
                });
            }
        });
    }

    private void testData() {
        valueList.clear();
        valueList.add(personBean.getName());
        valueList.add(personBean.getGender());
        valueList.add(personBean.getMatchNm());
        valueList.add(personBean.getRaceNum());
        valueList.add(personBean.getPhone());
        setValue();
    }

    private void setValue() {
        int childCount = ll_value.getChildCount();
        if (valueList.size() < childCount) {
            return;
        }
        for (int i = 0; i < childCount; i++) {
            EditText et = (EditText) ll_value.getChildAt(i);
            et.setText(valueList.get(i));
            et.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showMessageDialog("提示", "请咨询现场工作人员进行修改！", true, false);
                }
            });
        }
    }

    public void OnBack(View view) {
        gotoHome();
    }

    private void startTimeDown() {
        tv_count.startTimeDown(AppConstant.CountTime, 1, new CountTimes.OnCountTimeListener() {
            @Override
            public void onStart(int time) {
                tv_count.setText("" + time);
            }

            @Override
            public void onTick(int time) {
                tv_count.setText("" + time);
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onFinish(int time) {
                gotoHome();
            }
        });
    }

    private void releaseTimeDown() {
        tv_count.release();
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        tv_count.resetTime();
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startTimeDown();
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseTimeDown();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disConnect();
        unbindService();
    }

    /**
     * 更新人员领物状态
     */
    private void updatePersonInfo() {
        OkGo.<String>get(AppConstant.URL_UPDATE_STATUS).tag(this)
                .params("idCard", AppConstant.cardId)//证件号
                .params("matchId", AppConstant.matchId)//赛事id
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String body = response.body();
                        LogUtil.i(TAG, "updatePersonInfo()-->onSuccess: 更新人员领物状态成功，姓名：" + personBean.getName() + ";证件号：" + AppConstant.cardId);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        LogUtil.e(TAG, "updatePersonInfo()-->onError: 更新人员领物状态失败，姓名：" + personBean.getName() + ";证件号：" + AppConstant.cardId);
                    }

                    @Override
                    public void onFinish() {
                        hideProgressDialog();
                        showMessageDialog("提示", "打印成功！请取走您的领物单", false, true);
                    }
                });
    }

    //============打印机相关============

    private void bindService() {
        Intent intent = new Intent(this, PosprinterService.class);
        bindService(intent, mSerconnection, BIND_AUTO_CREATE);
    }

    private void unbindService() {
        if (mSerconnection != null) {
            unbindService(mSerconnection);
        }
    }

    ServiceConnection mSerconnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (IMyBinder) service;
            isBindService = true;
            if (MyApplication.isDebug) {
                Log.i(TAG, "onServiceConnected: ");
            }
            connectUsb();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            if (MyApplication.isDebug) {
                Log.i(TAG, "onServiceDisconnected: ");
            }
            isBindService = false;
        }
    };

    private void connectUsb() {
        List<String> usbList = PosPrinterDev.GetUsbPathNames(this);
        String dev = "";
        if (usbList != null && usbList.size() > 0) {
            dev = usbList.get(0);
            if (dev != null && !"".equals(dev)) {
                myBinder.ConnectUsbPort(getApplicationContext(), dev, new TaskCallback() {
                    @Override
                    public void OnSucceed() {
                        isConnect = true;
                        if (MyApplication.isDebug) {
                            Log.i(TAG, "OnSucceed: 连接成功");
                            Toast.makeText(getApplicationContext(), "连接成功", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void OnFailed() {
                        isConnect = false;
                        Log.i(TAG, "OnFailed: 连接失败");
                        Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

    private void disConnect() {
        if (isConnect) {
            myBinder.DisconnectCurrentPort(new TaskCallback() {
                @Override
                public void OnSucceed() {
                    isConnect = false;
//                    Toast.makeText(getApplicationContext(), "断开连接成功", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void OnFailed() {
                    isConnect = true;
//                    Toast.makeText(getApplicationContext(), "断开连接失败", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private Bitmap bitmap1;
    private Bitmap bitmap2;
    private SimpleDateFormat format;

    private int getBitmapResId() {
        int id;
        Context context = getBaseContext();
        if (personBean == null) {
            id = context.getResources().getIdentifier("img_print_null", "mipmap", context.getPackageName());
            return id;
        }
        String clothSize = personBean.getClotheSize();
        String bitmapName = "img_print_" + clothSize;
        id = context.getResources().getIdentifier(bitmapName, "mipmap", context.getPackageName());
        if (id == 0) {
            id = context.getResources().getIdentifier("img_print_null", "mipmap", context.getPackageName());
        }
        Log.i(TAG, "getBitmapResId: " + id);
        return id;
    }

    private void print() {
        if (isConnect) {
            showProgressDialog(false, "正在打印中");
            bitmap1 = BitmapFactory.decodeResource(getResources(), getBitmapResId());
            bitmap2 = BitmapFactory.decodeResource(getResources(), R.mipmap.img_print_qrcode);
            format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault());
            myBinder.CheckLinkedState(new TaskCallback() {
                @Override
                public void OnSucceed() {
                    Log.i(TAG, "OnSucceed: CheckLinkedState");
                }

                @Override
                public void OnFailed() {
                    Log.i(TAG, "OnFailed: CheckLinkedState");
                }
            });

            myBinder.WriteSendData(new TaskCallback() {
                @Override
                public void OnSucceed() {
                    LogUtil.i(TAG, "OnFailed: 打印成功 name=" + personBean.getName() + ";idCard=" + personBean.getIdCard());
                    if (MyApplication.isDebug) {
                        hideProgressDialog();
                        return;
                    }
                    Toast.makeText(getApplicationContext(), "打印成功", Toast.LENGTH_SHORT).show();
                    updatePersonInfo();//更新信息
                }

                @Override
                public void OnFailed() {
                    LogUtil.i(TAG, "OnFailed: 打印失败 name=" + personBean.getName() + ";idCard=" + personBean.getIdCard());
                    if (MyApplication.isDebug) {
                        Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();
                    }
                    hideProgressDialog();
                    showMessageDialog("提示", "打印失败！请取联系管理人员！", false, true);

                }
            }, new ProcessData() {
                @Override
                public List<byte[]> processDataBeforeSend() {
                    Log.i(TAG, "processDataBeforeSend: start ");
                    List<byte[]> list = new ArrayList<>();
                    //怎么获取状态值
//                    list.add(DataForSendToPrinterPos80.returnState(49));//1,2,49,50;1,49返回传感器状态,2,50返回钱箱状态;

                    //初始化
                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));//左中右对齐 0,1,2
                    list.add(DataForSendToPrinterPos80.selectOrCancelBoldModel(1));
                    //n的0到3位设定字符高度，4-7位用来设定字符宽度
                    //1111 1111 ，0，17，34，
                    list.add(DataForSendToPrinterPos80.selectCharacterSize(17));//字体放大一倍
                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(StringUtils.strTobytes(MyApplication.getMatchChNm()));
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(StringUtils.strTobytes(MyApplication.getMatchEnNm()));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(2));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(StringUtils.strTobytes("参赛号码"));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(2));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(DataForSendToPrinterPos80.selectOrCancelBoldModel(1));//0不加粗，1加粗
                    list.add(DataForSendToPrinterPos80.selectCharacterSize(17));
                    list.add(StringUtils.strTobytes(personBean.getRaceNum()));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(2));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(StringUtils.strTobytes(personBean.getMatchNm()));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(StringUtils.strTobytes("打印时间 " + format.format(new Date())));
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(StringUtils.strTobytes("技术支持：蜂之舞芯片计时"));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(StringUtils.strTobytes("------------------------------"));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.setAbsolutePrintPosition(100, 00));
                    list.add(StringUtils.strTobytes("参赛号：" + personBean.getRaceNum()));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.setAbsolutePrintPosition(100, 00));
                    list.add(StringUtils.strTobytes("姓名：" + personBean.getName()));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.setAbsolutePrintPosition(100, 00));
                    list.add(StringUtils.strTobytes("性别：" + personBean.getGender()));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.setAbsolutePrintPosition(100, 00));
                    list.add(StringUtils.strTobytes("证件号：" + personBean.getIdCard()));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(StringUtils.strTobytes("参赛包+参赛服领取"));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    //图片
                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    List<Bitmap> blist1 = new ArrayList<>();
                    blist1 = BitmapProcess.cutBitmap(150, bitmap1);
                    for (int i = 0; i < blist1.size(); i++) {
                        list.add(DataForSendToPrinterPos80.printRasterBmp(0, blist1.get(i), BitmapToByteData.BmpType.Dithering, BitmapToByteData.AlignType.Center, 576));
                    }
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(StringUtils.strTobytes("请撕下此联！以免影响物资领取"));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(StringUtils.strTobytes("Please don't tear this down"));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(StringUtils.strTobytes("------------------------------"));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(StringUtils.strTobytes("号码簿芯片领取窗口"));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(StringUtils.strTobytes("Bib Number&Chips Counter"));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    list.add(DataForSendToPrinterPos80.selectAlignment(1));
                    list.add(DataForSendToPrinterPos80.selectOrCancelBoldModel(1));//0不加粗，1加粗
                    list.add(DataForSendToPrinterPos80.selectCharacterSize(34));
                    list.add(StringUtils.strTobytes(personBean.getGetWindow()));
//                    list.add(DataForSendToPrinterPos80.setLineSpaceing(10));//设置行间距 0-255
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    //图片
                    list.add(DataForSendToPrinterPos80.initializePrinter());
                    List<Bitmap> blist2 = new ArrayList<>();
                    blist2 = BitmapProcess.cutBitmap(150, bitmap2);
                    for (int i = 0; i < blist2.size(); i++) {
                        list.add(DataForSendToPrinterPos80.printRasterBmp(0, blist2.get(i), BitmapToByteData.BmpType.Dithering, BitmapToByteData.AlignType.Center, 576));
                    }
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());

                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    list.add(DataForSendToPrinterPos80.selectCutPagerModerAndCutPager(0));
//                    list.add(DataForSendToPrinterPos80.selectCutPagerModerAndCutPager(1));
//                    list.add(DataForSendToPrinterPos80.selectCutPagerModerAndCutPager(48));
//                    list.add(DataForSendToPrinterPos80.selectCutPagerModerAndCutPager(49));
                    Log.i(TAG, "processDataBeforeSend: end ");
                    return list;
                }
            });
        } else {
            Log.i(TAG, "print: 打印机未连接");
            Toast.makeText(this, "打印机未连接", Toast.LENGTH_SHORT).show();
        }
    }
}
